package com.cloud.lan.aop;

import com.alibaba.fastjson.JSON;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

/**
 * RequestClientAspect
 * @author ErKang
 * @date Created in 2021/12/6 23:40
 * @title RequestClientAspect.java
 * Department: Product development
 */
@Component
@Aspect
@Slf4j
public class RequestClientAspect {

    @Pointcut("@annotation(com.cloud.lan.aop.RequestClient)")
    public void pointcut() {}

    @Around(value = "pointcut()")
    public Object requestClient(ProceedingJoinPoint pjp) throws Throwable {
        String methodName = pjp.getSignature().getName();
        Object[] args = pjp.getArgs();
        Object rpcResult = null;
        long startTime = System.currentTimeMillis();
        log.info("method name =>[{}], request param =>[{}]", methodName, JSON.toJSON(args));
        try {
            rpcResult = pjp.proceed();
            long endTime = System.currentTimeMillis();
            log.info(
                    "method name =>[{}], request param =>[{}], response => [{}] cost => [{}]",
                    methodName,
                    args,
                    JSON.toJSON(rpcResult),
                    endTime - startTime);
            return rpcResult;

        } catch (Exception e) {
            log.error(
                    "请求资源出现问题 method=[{}] args=[{}] response=[{}]",
                    methodName,
                    args,
                    JSON.toJSON(rpcResult),
                    e);
            throw e;
        }
    }
}
